package com.example.campuslink.ui.fragment

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.example.campuslink.viewModel.BaseViewModel

abstract class BaseFragment<V : ViewDataBinding, VM : BaseViewModel>(
    private val vmClass: Class<VM>,
    private val layoutId: Int,
    private val viewModelId: Int
) : Fragment() {
    protected var mViewDataBinding: V? = null
    protected var mViewModel: VM? = null
    protected var isPause = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mViewDataBinding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        mViewModel = ViewModelProvider(getViewModelStoreOwner())[vmClass]
        if (viewModelId != 0) {
            mViewDataBinding?.setVariable(viewModelId, mViewModel)
        }
        mViewDataBinding?.lifecycleOwner = this
        initActJumpData()
        initData()
        initViews()
        onClick()
        return mViewDataBinding?.root
    }

    abstract fun onClick()

    abstract fun initViews()

    open fun getViewModelStoreOwner(): ViewModelStoreOwner = this

    protected fun setNavigationStatusColor(color: Int) {
        activity?.window?.let {
            it.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        }
    }

    private fun initActJumpData() {
        if (mViewModel?.actJumpLiveData?.hasObservers() == true) {
            return
        }
        try {
            mViewModel?.actJumpLiveData?.observe(viewLifecycleOwner) { data ->
                if (data.isDeprecated) {
                    return@observe
                }
                data.targetClass?.let {
                    (data.targetIntent ?: Intent()).apply {
                        component = ComponentName(requireActivity(), it)
                    }.also {
                        startActivity(it)
                    }
                }
                if (data.finishCurrent) {
                    data.activityResult?.let {
                        requireActivity().setResult(it.resultCode, it.data)
                    }
                    requireActivity().finish()
                }
                data.isDeprecated = true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        isPause = false
    }

    override fun onPause() {
        super.onPause()
        isPause = true
    }

    abstract fun initData()
}